package org.youyee.game.utils
{
	import org.youyee.game.displayArea.Area;
	import org.youyee.game.pathFinding.PathMap;
	import org.youyee.game.pathFinding.PathNode;
	
	import flash.display.Sprite;
	import flash.utils.getDefinitionByName;

	/**
	 * 地板生成器 
	 * @author youyee
	 * 
	 */	
	public class FloorGenerator
	{
		/**
		 * 生成地板 
		 * @param area 需要执行被生成地板的区域
		 * @param floorClasses 地板的类名数列
		 * @param defaultFloorClassName 默认的缺省地板
		 * @param createFloorMethod 创建地板的方法函数，默认不使用
		 * @return 创建好的序列
		 * 
		 */		
		public static function generateFloor(area:Area, floorClasses:Array, defaultFloorClassName:String="", createFloorMethod:Function=null):Array
		{
			var floors:Array = [];
			var len:int = area.areaSize;
			var f:Sprite;
			var p:PathNode;
			var pathMap:PathMap = area.pathMap;
			
			for (var i:int=0; i<len; ++i)
			{
				p = pathMap.getPathNodeByPosition(i % pathMap.width, int(i / pathMap.width));
				
				if (createFloorMethod != null)
				{
					f = createFloorMethod(floorClasses[i], p) as Sprite;
				}
				else
				{
					f = createFloorByClass(floorClasses[i] ? floorClasses[i] as String : defaultFloorClassName, p) as Sprite;
				}
				
				if (f)
				{
					area.floorLayer.addChild(f);
					floors.push(f);
				}
			}
			
			f = null;
			
			return floors;
		}
		
		/**
		 * 如果需要有异步加载的需求，请复写此方法来创建地板 
		 * @param className 类的名称
		 * @return 创建好的地板对象
		 * 
		 */		
		protected static function createFloorByClass(className:String, pathNode:PathNode):Sprite
		{
			if (!className)
			{
				return null;
			}
			
			var floorClass:Class;
			var f:Sprite;
			
			try
			{
				floorClass = getDefinitionByName(className) as Class;
			}
			catch (e:Error){}
			
			if (floorClass)
			{
				f = new floorClass() as Sprite;
			}
			else
			{
				//走一个容错的逻辑
				f = new Sprite();
			}
			
			PositionCalculator.setObjectPositionByPathNode(f, pathNode);
			return f;
		}
	}
}